<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="商品ID" prop="goodsId">
        <el-input
          v-model="queryParams.goodsId"
          placeholder="请输入商品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="商品名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格名称" prop="specValueName">
        <el-input
          v-model="queryParams.specValueName"
          placeholder="请输入规格名称"
          clearable
          @keyup.enter.native="handleQuery"
          class="long-input"
        />
      </el-form-item>
      <el-form-item label="规格条码" prop="skuBarCode">
        <el-input
          v-model="queryParams.skuBarCode"
          placeholder="请输入规格条码"
          clearable
          @keyup.enter.native="handleQuery"
          class="long-input"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:goodsInfo:batchInsertGoodsByWm']"
        >获取
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:goodsInfo:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:goodsInfo:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
                   v-hasPermi="['business:goodsInfo:import']">导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:goodsInfo:export']"
        >导出
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsInfoList" @selection-change="handleSelectionChange" border height="650">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column
        label="序号"
        type="index"
        width="50"
        align="center"
        :index="(i) => (pageSize * (pageNum - 1)) + i + 1"
      />
      <el-table-column label="商品ID" align="center" prop="goodsId" width="150px"/>
      <el-table-column label="商品名称" align="center" prop="title" width="110px"/>
      <el-table-column label="规格名称" align="center" prop="specValueName" width="150px"/>
      <el-table-column label="规格编码" align="center" prop="outerSkuCode" width="180px"/>
      <el-table-column label="规格条码" align="center" prop="skuBarCode" width="150px"/>
      <el-table-column label="商品单价" align="center" prop="salePrice"/>
      <el-table-column label="商品数量" align="center" prop="skuNum"/>
      <el-table-column label="SKUID" align="center" prop="skuId" width="150px"/>
      <el-table-column prop="categoryId" label="类目" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_goods_category" :value="scope.row.categoryId"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <!-- <el-table-column label="状态" align="center" prop="status"/>-->
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="updateBy"/>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:goodsInfo:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:goodsInfo:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="规格编码" prop="outerSkuCode">
          <el-input v-model="form.outerSkuCode" placeholder="请输入商品规格编码" :disabled="true"/>
        </el-form-item>
        <el-form-item label="规格条码" prop="skuBarCode">
          <el-input v-model="form.skuBarCode" type="textarea" placeholder="请输入规格条码" :disabled="true"/>
        </el-form-item>
        <el-form-item label="销售价格" prop="salePrice">
          <el-input v-model="form.salePrice" placeholder="请输入商品销售价格" :disabled="true"/>
        </el-form-item>
        <el-form-item label="商品数量" prop="skuNum">
          <el-input v-model="form.skuNum" placeholder="请输入商品数量" :disabled="true"/>
        </el-form-item>
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="form.title" type="textarea" placeholder="请输入商品名称" :disabled="true"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                 :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                 :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="获取商品信息" :visible.sync="openWmGoodsVisible" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品编号" prop="goodsId">
          <el-input
            type="textarea"
            v-model="form.goodsId"
            :autosize="{ minRows: 4, maxRows: 10 }"
            placeholder="输入客户编号，最大支持一次查询 20 条，用逗号分隔"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormWm">确 定</el-button>
        <el-button @click="cancelWm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addGoodsInfo,
    delGoodsInfo,
    fetchFromWeimob,
    getGoodsInfo,
    listGoodsInfo,
    updateGoodsInfo
  } from "@/api/business/goodsInfo";
  import {getToken} from '@/utils/auth'

  export default {
    name: "GoodsInfo",
    dicts: ['sys_goods_category'],
    data() {
      return {
        upload: {
          // 是否显示弹出层（商品信息导入）
          open: false,
          // 弹出层标题（商品信息导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + '/business/goodsInfo/importGoodsInfoFile',
        },
        isEditMode: false, // ➤ 当前是否为编辑模式
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商品信息表格数据
        goodsInfoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        //微盟弹出框
        openWmGoodsVisible: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 30,
          outerSkuCode: null,
          salePrice: null,
          skuId: null,
          skuNum: null,
          title: null,
          goodsId: null,
          categoryId: null,
          status: null,
        },
        // 表单参数
        form: {},
        para: {
          "goodsId": null,
        },
        // 表单校验
        rules: {},
        pageNum: 1,
        pageSize: 50,
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 打开导入弹框 */
      handleImport() {
        this.upload.title = "商品信息导入";
        this.upload.open = true;
      },
      handleImportSuccess(response) {
        this.$modal.msgSuccess('导入成功');
        this.importDialogVisible = false;
        this.getList(); // 重新加载数据
      },
      handleImportError(err) {
        this.$modal.msgError('导入失败');
      },
      beforeUpload(file) {
        const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        if (!isExcel) {
          this.$modal.msgError('只能上传Excel文件');
        }
        return isExcel;
      },
      /** 查询商品信息列表 */
      getList() {
        this.loading = true;
        listGoodsInfo(this.queryParams).then(response => {
          this.goodsInfoList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          outerSkuCode: null,
          salePrice: null,
          skuId: null,
          skuNum: null,
          title: null,
          goodsId: null,
          categoryId: null,
          remark: null,
          createTime: null,
          createBy: null,
          updateTime: null,
          updateBy: null,
          skuBarCode: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.skuBarCode)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        const msg = response.message || response.msg || '导入完成';
        this.$alert(
          `<div style='overflow:auto;overflow-x:hidden;max-height:70vh;padding:10px 20px 0;'>${msg}</div>`,
          "导入结果",
          {dangerouslyUseHTMLString: true}
        );
        // 如果成功才刷新列表
        if (response.code === 200) {
          this.getList();
        }
      },
      // 下载模板
      importTemplate() {
        this.download(
          '/business/goodsInfo/importTemplate',
          {},
          `商品导入_模版_${new Date().getTime()}.xlsx`
        );
      },
      // 文件上传过程中的处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 提交上传表单，触发文件上传
      submitFileForm() {
        this.$refs.upload.submit();
      },
      /**  从微盟获取商品信息  */
      handleAdd() {
        this.reset();
        this.openWmGoodsVisible = true;
        this.title = "获取商品信息";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const skuBarCode = row.skuBarCode || this.ids
        getGoodsInfo(skuBarCode).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改商品信息";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.skuBarCode != null) {
              updateGoodsInfo(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addGoodsInfo(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const skuBarCodes = row.skuBarCode || this.ids;
        this.$modal.confirm('是否确认删除商品信息编号为"' + skuBarCodes + '"的数据项？').then(function () {
          return delGoodsInfo(skuBarCodes);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 获取按钮 */
      submitFormWm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            let rawInput = this.form.goodsId;
            // 替换中文逗号为英文逗号，并转为数字数组
            let goodsIdArray = rawInput
              .replace(/，/g, ',')
              .split(',')
              .map(item => item.trim())
              .filter(item => item !== '')
              .map(item => Number(item));

            // 验证格式
            if (goodsIdArray.some(isNaN)) {
              this.$modal.msgError("商品编号格式有误，请输入纯数字，并用英文逗号分隔");
              return;
            }

            // 去重
            let uniqueGoodsIds = [...new Set(goodsIdArray)];

            // 数量限制
            if (uniqueGoodsIds.length > 20) {
              this.$modal.msgError("最多只能查询 20 个商品编号");
              return;
            }

            // 调用接口
       /*     let para = {
              "goodsId": this.uniqueGoodsIds,
            };*/
           // this.para.goodsId = this.form.goodsId;
            fetchFromWeimob(uniqueGoodsIds).then(res => {
              this.$modal.msgSuccess("获取商品信息成功");
              this.openWmGoodsVisible = false;
              this.getList();
            });
          }
        });
      },
      cancelWm() {
        this.openWmGoodsVisible = false;
        this.reset();
      },


      /** 导出按钮操作 */
      handleExport() {
        this.download('business/goodsInfo/export', {
          ...this.queryParams
        }, `goodsInfo_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style scoped>
  .long-input {
    width: 300px; /* 固定宽度 */
  }
</style>
